package com.kuaifawu.lwnlawyerclient.Fragment;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Activity.MainActivity;

import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.fb.SyncListener;
import com.umeng.fb.model.Conversation;
import com.umeng.fb.model.Reply;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class LWNFeedbackFragment extends Fragment {

    @ViewInject(R.id.fb_reply_list)
    private ListView mListView;
    @ViewInject(R.id.fb_send_btn)
    private Button sendBtn;
    @ViewInject(R.id.fb_send_content)
    private AutoCompleteTextView inputEdit;
    @ViewInject(R.id.fb_reply_refresh)
    private SwipeRefreshLayout mSwipeRefreshLayout;

    private FeedbackAgent mAgent;
    private Conversation mComversation;
    private Context mContext;
    private ReplyAdapter adapter;
    private MainActivity activity_self;

    private final int VIEW_TYPE_COUNT = 2;
    private final int VIEW_TYPE_USER = 0;
    private final int VIEW_TYPE_DEV = 1;
    private final String TAG = LWNFeedbackFragment.class.getName();

    public LWNFeedbackFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_lwnfeedback, container, false);
        ViewUtils.inject(this, rootView);
        mContext = getActivity();
        mAgent = new FeedbackAgent(getActivity());
        mComversation = new FeedbackAgent(getActivity()).getDefaultConversation();
        adapter = new ReplyAdapter();
        mListView.setAdapter(adapter);
        sync();
        initView();
        return rootView;
    }

    public void LoadFeedbackWithActivity() {
        sync();
    }

    private void initView() {
        inputEdit.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToBottom();
            }
        });

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputEdit.getText().toString();
                inputEdit.getEditableText().clear();
                if (!TextUtils.isEmpty(content)) {
//                    LWNNetworkCenter center = LWNNetworkCenter.getInstance();
//                    if(!center.checkNetworkState(getActivity())) {
//                        ToastView_custom toast = new ToastView_custom(getActivity());
//                        toast.showCustom(getActivity(), getResources().getDrawable(R.drawable.error), "检查网络，稍后重试");
//                        return;
//                    }
                    // 将内容添加到会话列表
                    mComversation.addUserReply(content);
                    //刷新ListView
                    adapter.notifyDataSetChanged();
                    scrollToBottom();
                    // 数据同步
                    sync();
                }else{
                    ToastView_custom toast = new ToastView_custom(getActivity());
                    toast.showCustom(getActivity(), "网络错误，稍后重试");

                }
            }
        });

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            int listViewScrollState;
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listViewScrollState = scrollState;
                switch (scrollState) {
                    //空闲状态
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: {
                    }
                    break;
                    //滚动状态
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING: {

                    }
                    break;
                    //触摸后滚动
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: {
                        closeKeyBoard();
                    }
                    break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });


        //下拉刷新
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                sync();
            }


        });
    }

    // 数据同步
    private void sync() {

        mComversation.sync(new SyncListener() {

            @Override
            public void onSendUserReply(List<Reply> replyList) {

            }

            @Override
            public void onReceiveDevReply(List<Reply> replyList) {
                // SwipeRefreshLayout停止刷新
                //mSwipeRefreshLayout.setRefreshing(false);
                // 刷新ListView

                scrollToBottom();
            }


        });
    }

    private void scrollToBottom() {
        if (adapter.getCount() > 0) {//adapter.getCount()
            mListView.smoothScrollToPosition(adapter.getCount());
            if(mSwipeRefreshLayout.isRefreshing()){
                mSwipeRefreshLayout.setRefreshing(false);

                mListView.smoothScrollToPosition(0);
                adapter.notifyDataSetChanged();
            }else{
                adapter.notifyDataSetChanged();
                mListView.smoothScrollToPosition(adapter.getCount());
            }
        }

    }

    // adapter
    class ReplyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mComversation.getReplyList().size();
        }

        @Override
        public Object getItem(int arg0) {
            return mComversation.getReplyList().get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public int getViewTypeCount() {
            // 两种不同的Item布局
            return VIEW_TYPE_COUNT;
        }

        @Override
        public int getItemViewType(int position) {
            // 获取单条回复
            Reply reply = mComversation.getReplyList().get(position);
            if (Reply.TYPE_DEV_REPLY.equals(reply.type)) {
                // 开发者回复Item布局
                return VIEW_TYPE_DEV;
            } else {
                // 用户反馈、回复Item布局
                return VIEW_TYPE_USER;
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            // 获取单条回复
            Reply reply = mComversation.getReplyList().get(position);
            if (convertView == null) {
                // 根据Type的类型来加载不同的Item布局
                if (Reply.TYPE_DEV_REPLY.equals(reply.type)) {
                    // 开发者的回复
                    convertView = LayoutInflater.from(mContext).inflate(
                            R.layout.custom_fb_dev_reply, null);
                } else {
                    // 用户的反馈、回复
                    convertView = LayoutInflater.from(mContext).inflate(
                            R.layout.custom_fb_user_reply, null);
                }

                // 创建ViewHolder并获取各种View
                holder = new ViewHolder();
                holder.replyContent = (TextView) convertView
                        .findViewById(R.id.fb_reply_content);
                holder.replyProgressBar = (ProgressBar) convertView
                        .findViewById(R.id.fb_reply_progressBar);
                holder.replyStateFailed = (ImageView) convertView
                        .findViewById(R.id.fb_reply_state_failed);
                holder.replyData = (TextView) convertView
                        .findViewById(R.id.fb_reply_date);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            // 以下是填充数据
            // 设置Reply的内容
            holder.replyContent.setText(reply.content);
            // 在App应用界面，对于开发者的Reply来讲status没有意义
            if (!Reply.TYPE_DEV_REPLY.equals(reply.type)) {
                // 根据Reply的状态来设置replyStateFailed的状态
                if (Reply.STATUS_NOT_SENT.equals(reply.status)) {
                    holder.replyStateFailed.setVisibility(View.VISIBLE);
                } else {
                    holder.replyStateFailed.setVisibility(View.GONE);
                }

                // 根据Reply的状态来设置replyProgressBar的状态
                if (Reply.STATUS_SENDING.equals(reply.status)) {
                    holder.replyProgressBar.setVisibility(View.VISIBLE);
                } else {
                    holder.replyProgressBar.setVisibility(View.GONE);
                }
            }

            // 回复的时间数据，两条Reply之间相差100000ms则展示时间
            if ((position + 1) < mComversation.getReplyList().size()) {
                Reply nextReply = mComversation.getReplyList()
                        .get(position + 1);
                if (nextReply.created_at - reply.created_at > 100000) {
                    Date replyTime = new Date(reply.created_at);
                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "yyyy-MM-dd HH:mm");
                    holder.replyData.setText(sdf.format(replyTime));
                    holder.replyData.setVisibility(View.VISIBLE);
                }
            }
            return convertView;
        }

        class ViewHolder {
            TextView replyContent;
            ProgressBar replyProgressBar;
            ImageView replyStateFailed;
            TextView replyData;
        }
    }

    public void closeKeyBoard(){
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(inputEdit.getWindowToken(), 0);
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");
      //  MobclickAgent.onResume(getActivity());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
        //MobclickAgent.onPause(getActivity());
    }
}
